package pl.edu.agh.uhm.upnp.discoverer;

import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

import org.osgi.framework.ServiceReference;
import org.osgi.service.upnp.UPnPDevice;
import org.osgi.util.tracker.ServiceTracker;

import pl.edu.agh.uhm.discoverer.VirtualMachine;

public class UPnPBasedVirtualMachine implements VirtualMachine{

	
	ServiceTracker serviceTracker;
	private final String id; 
	
	public UPnPBasedVirtualMachine(ServiceReference device){
		
		Object udn= device.getProperty(UPnPDevice.UDN);
		if(udn!=null)
			id=(String)udn;
		else
			id="UNKNOWN";
		serviceTracker=new ServiceTracker(Activator.context,device, null);
		serviceTracker.open();
		
	}
	

	@Override
	public void start() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void stop() {
		// TODO Auto-generated method stub
		
	}

	public String toString(){
		StringBuilder sb=new StringBuilder();
		sb.append("---UPnP Based Virtual Machine---\n");
		UPnPDevice upnpDevice=(UPnPDevice)serviceTracker.getService();
		if(upnpDevice==null)
			sb.append("Cannot found related UPnP device");
		else{
			Dictionary dict=upnpDevice.getDescriptions(null);
			Enumeration keys=dict.keys();
			while(keys.hasMoreElements()){
				String key=(String)keys.nextElement();
				sb.append(key);
				sb.append("=");
				sb.append(dict.get(key));
				sb.append("\n");
			}			
		}
		return sb.toString();
		
	}

	@Override
	public String getParentId() {
		UPnPDevice upnpDevice=(UPnPDevice)serviceTracker.getService();
		if(upnpDevice==null)
			return null;
		else{
			Dictionary dict=upnpDevice.getDescriptions(null);
			String parentId=(String)dict.get(UPnPDevice.CHILDREN_UDN);
			
			return parentId;
		}
	}


	@Override
	public String getId() {
		return id;
	}
	
}
